package com.mtsmda.ws.rest.jboss.services;

import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/query")
public class QueryService {

	@GET
	@Path("/q")
	public Response getQueryParam(@QueryParam("from") String tableName,
			@QueryParam("id") int id,
			@QueryParam("orderBy") List<String> orderBy) {
		StringBuilder sb = new StringBuilder();
		if (!orderBy.isEmpty()) {
			for (int i = 0; i < orderBy.size(); i++) {
				if (i == orderBy.size() - 1) {
					sb.append(orderBy.get(i)).append(";");
				} else {
					sb.append(orderBy.get(i)).append(",");
				}
			}
		}

		String sql = "Select * from " + tableName + " where id = " + id
				+ " order by " + sb.toString();

		return Response.status(200).entity(sql).build();
	}

	@GET
	@Path("/qq")
	public Response getQueryParam(@Context UriInfo info) {
		String tableName = info.getQueryParameters().getFirst("from");
		String id = info.getQueryParameters().getFirst("id");
		List<String> orderBy = info.getQueryParameters().get("orderBy");

		StringBuilder sb = new StringBuilder();
		if (!orderBy.isEmpty()) {
			for (int i = 0; i < orderBy.size(); i++) {
				if (i == orderBy.size() - 1) {
					sb.append(orderBy.get(i)).append(";");
				} else {
					sb.append(orderBy.get(i)).append(",");
				}
			}
		}

		String sql = "QQ - Select * from " + tableName + " where id = " + id
				+ " order by " + sb.toString();

		return Response.status(200).entity(sql).build();
	}

	@GET
	@Path("/qqq")
	public Response getQueryParamQQQ(
			@DefaultValue(value = "admin") @QueryParam("from") String tableName,
			@DefaultValue(value = "19") @QueryParam("id") int id,
			@DefaultValue(value = "isAdmin") @QueryParam("orderBy") List<String> orderBy) {
		StringBuilder sb = new StringBuilder();
		if (!orderBy.isEmpty()) {
			for (int i = 0; i < orderBy.size(); i++) {
				if (i == orderBy.size() - 1) {
					sb.append(orderBy.get(i)).append(";");
				} else {
					sb.append(orderBy.get(i)).append(",");
				}
			}
		}

		String sql = "Select * from " + tableName + " where id = " + id
				+ " order by " + sb.toString();

		return Response.status(200).entity(sql).build();
	}

	@GET
	@Path("/year/{year}")
	public Response getQueryMatrix(@PathParam("year") int year,
			@MatrixParam("author") String author,
			@MatrixParam("book") String book) {
		String n = "Matrix - year: " + year + ";<br>Author - " + author + "<br>Book - " + book;
		
		return Response.status(200).entity(n).build();
	}

}